AWSTemplateFormatVersion: '2010-09-09'
Description: >
  Unattached EBS Volume Remediator.
  Purpose-specific, opt-in remediation module for identifying unattached EBS volumes
  and optionally snapshotting and/or deleting eligible volumes. This template is
  separate from the cost optimization assessment/reporting template.

Parameters:
  ProjectName:
    Type: String
    Default: unattached-ebs-volume-remediator
    Description: Base name used for created resources.

  TargetRegionsCsv:
    Type: String
    Default: all-enabled
    Description: Comma-separated AWS Regions to scan, or all-enabled to scan all enabled Regions.

  ExcludedRegionsCsv:
    Type: String
    Default: ap-northeast-3
    Description: Comma-separated AWS Regions to exclude from scanning/remediation.

  DryRun:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: When true, only report what would be changed. When false, perform eligible actions.

  MinimumUnattachedAgeDays:
    Type: Number
    Default: 30
    Description: Only unattached volumes older than this many days are considered candidates.

  RequireApprovalTag:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: >
      When true, only act on candidate volumes tagged with ApprovalTagKey=ApprovalTagValue.
      For large backlog cleanup, set false only after reviewing dry-run results.

  ApprovalTagKey:
    Type: String
    Default: CostOptApproved
    Description: Tag key required when RequireApprovalTag is true.

  ApprovalTagValue:
    Type: String
    Default: 'true'
    Description: Tag value required when RequireApprovalTag is true.

  IgnoreTagKeysCsv:
    Type: String
    Default: CostOptIgnore,DoNotDelete
    Description: Comma-separated tag keys that prevent action when present, regardless of value.

  IgnoreTagPairsCsv:
    Type: String
    Default: CostOptIgnore=true,DoNotDelete=true
    Description: Comma-separated key=value tag pairs that prevent action when present.

  ActionMode:
    Type: String
    Default: report-only
    AllowedValues:
      - report-only
      - snapshot-only
      - delete-only
      - snapshot-and-delete
    Description: >
      Action to take for eligible unattached volumes. report-only never changes resources.
      snapshot-only creates a snapshot. delete-only deletes without creating a snapshot.
      snapshot-and-delete creates a snapshot first, then deletes the volume.

  SnapshotBeforeDelete:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Additional safety control. When true, delete actions require a snapshot first.

  SnapshotDescriptionPrefix:
    Type: String
    Default: CostOpt remediation snapshot before unattached EBS volume deletion
    Description: Description prefix used when creating remediation snapshots.

  MaxVolumesPerRun:
    Type: Number
    Default: 50
    Description: Safety limit. 0 means no limit. Recommended first cleanup batch is 25 to 100.

  ContinueOnAccessDenied:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Continue scanning other Regions/resources when blocked by IAM/SCP.

  ScheduleEnabled:
    Type: String
    Default: 'false'
    AllowedValues: ['true', 'false']
    Description: Whether to create an enabled EventBridge schedule for recurring runs.

  ScheduleExpression:
    Type: String
    Default: rate(30 days)
    Description: EventBridge schedule expression used when ScheduleEnabled is true.

Conditions:
  IsScheduleEnabled: !Equals [!Ref ScheduleEnabled, 'true']

Resources:
  RemediatorRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub '${ProjectName}-${AWS::AccountId}-${AWS::Region}-role'
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: UnattachedEbsVolumeRemediationPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: DiscoverRegions
                Effect: Allow
                Action:
                  - ec2:DescribeRegions
                Resource: '*'
              - Sid: ReadVolumesAndTags
                Effect: Allow
                Action:
                  - ec2:DescribeVolumes
                  - ec2:DescribeTags
                Resource: '*'
              - Sid: CreateSnapshotsAndTags
                Effect: Allow
                Action:
                  - ec2:CreateSnapshot
                  - ec2:CreateTags
                Resource: '*'
              - Sid: DeleteVolumes
                Effect: Allow
                Action:
                  - ec2:DeleteVolume
                Resource: '*'

  RemediatorFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Ref ProjectName
      Description: Purpose-specific remediation Lambda for unattached EBS volumes.
      Runtime: python3.12
      Handler: index.handler
      Timeout: 900
      MemorySize: 512
      Role: !GetAtt RemediatorRole.Arn
      Environment:
        Variables:
          TARGET_REGIONS_CSV: !Ref TargetRegionsCsv
          EXCLUDED_REGIONS_CSV: !Ref ExcludedRegionsCsv
          DRY_RUN: !Ref DryRun
          MINIMUM_UNATTACHED_AGE_DAYS: !Ref MinimumUnattachedAgeDays
          REQUIRE_APPROVAL_TAG: !Ref RequireApprovalTag
          APPROVAL_TAG_KEY: !Ref ApprovalTagKey
          APPROVAL_TAG_VALUE: !Ref ApprovalTagValue
          IGNORE_TAG_KEYS_CSV: !Ref IgnoreTagKeysCsv
          IGNORE_TAG_PAIRS_CSV: !Ref IgnoreTagPairsCsv
          ACTION_MODE: !Ref ActionMode
          SNAPSHOT_BEFORE_DELETE: !Ref SnapshotBeforeDelete
          SNAPSHOT_DESCRIPTION_PREFIX: !Ref SnapshotDescriptionPrefix
          MAX_VOLUMES_PER_RUN: !Ref MaxVolumesPerRun
          CONTINUE_ON_ACCESS_DENIED: !Ref ContinueOnAccessDenied
      Code:
        ZipFile: |
          import json
          import os
          import traceback
          from datetime import datetime, timezone

          import boto3
          from botocore.exceptions import ClientError

          def utc_now():
              return datetime.now(timezone.utc)

          def utc_now_iso():
              return utc_now().isoformat()

          def env_bool(name, default=False):
              value = os.environ.get(name, str(default)).strip().lower()
              return value in ('1', 'true', 'yes', 'y')

          def env_int(name, default=0):
              try:
                  return int(os.environ.get(name, str(default)).strip())
              except Exception:
                  return default

          def split_csv(value):
              if value is None:
                  return []
              return [item.strip() for item in str(value).split(',') if item.strip()]

          def parse_tag_pairs(value):
              pairs = {}
              for item in split_csv(value):
                  if '=' not in item:
                      continue
                  key, val = item.split('=', 1)
                  key = key.strip()
                  val = val.strip()
                  if key:
                      pairs[key] = val
              return pairs

          def tags_to_dict(tags):
              result = {}
              for tag in tags or []:
                  key = tag.get('Key')
                  if key:
                      result[key] = tag.get('Value', '')
              return result

          def get_enabled_regions(excluded_regions):
              requested = os.environ.get('TARGET_REGIONS_CSV', 'all-enabled').strip()
              if requested and requested.lower() != 'all-enabled':
                  regions = split_csv(requested)
              else:
                  ec2 = boto3.client('ec2', region_name=os.environ.get('AWS_REGION', 'us-east-1'))
                  response = ec2.describe_regions(AllRegions=False)
                  regions = sorted([r['RegionName'] for r in response.get('Regions', [])])
              return [r for r in regions if r not in excluded_regions]

          def volume_age_days(volume):
              create_time = volume.get('CreateTime')
              if not create_time:
                  return None
              if create_time.tzinfo is None:
                  create_time = create_time.replace(tzinfo=timezone.utc)
              return (utc_now() - create_time).days

          def has_ignore_tag(tag_map, ignore_tag_keys, ignore_tag_pairs):
              for key in ignore_tag_keys:
                  if key in tag_map:
                      return True, 'ignore_tag_key=' + key
              for key, value in ignore_tag_pairs.items():
                  if tag_map.get(key) == value:
                      return True, 'ignore_tag_pair=' + key + '=' + value
              return False, ''

          def has_approval_tag(tag_map, settings):
              if not settings['require_approval_tag']:
                  return True
              return tag_map.get(settings['approval_tag_key']) == settings['approval_tag_value']

          def create_remediation_snapshot(ec2, volume, region):
              volume_id = volume.get('VolumeId')
              tag_map = tags_to_dict(volume.get('Tags', []))
              name = tag_map.get('Name', '')
              description = os.environ.get('SNAPSHOT_DESCRIPTION_PREFIX', 'CostOpt remediation snapshot before unattached EBS volume deletion')
              description = description + ' | volume=' + str(volume_id) + ' | created=' + utc_now_iso()
              response = ec2.create_snapshot(VolumeId=volume_id, Description=description)
              snapshot_id = response.get('SnapshotId')
              tags = [
                  {'Key': 'CreatedBy', 'Value': 'unattached-ebs-volume-remediator'},
                  {'Key': 'SourceVolumeId', 'Value': str(volume_id)},
                  {'Key': 'CostOptRemediation', 'Value': 'true'},
                  {'Key': 'CreatedAt', 'Value': utc_now_iso()}
              ]
              if name:
                  tags.append({'Key': 'Name', 'Value': 'remediation-backup-' + name})
              if snapshot_id:
                  ec2.create_tags(Resources=[snapshot_id], Tags=tags)
              return snapshot_id

          def scan_region(region, settings):
              ec2 = boto3.client('ec2', region_name=region)
              result = {
                  'region': region,
                  'evaluated': 0,
                  'unattached': 0,
                  'eligible': 0,
                  'would_snapshot': 0,
                  'snapshots_created': 0,
                  'would_delete': 0,
                  'deleted': 0,
                  'skipped_attached': 0,
                  'skipped_too_new': 0,
                  'skipped_missing_approval_tag': 0,
                  'skipped_ignore_tag': 0,
                  'access_denied': 0,
                  'failed': 0,
                  'failures': [],
                  'candidates': [],
                  'snapshots': [],
                  'deleted_volumes': []
              }

              try:
                  paginator = ec2.get_paginator('describe_volumes')
                  pages = paginator.paginate()
              except ClientError as e:
                  code = e.response.get('Error', {}).get('Code', 'Unknown')
                  message = e.response.get('Error', {}).get('Message', str(e))
                  result['failures'].append({'operation': 'DescribeVolumes', 'error_code': code, 'error_message': message})
                  if code in ('AccessDenied', 'AccessDeniedException', 'UnauthorizedOperation') or 'explicit deny' in message.lower():
                      result['access_denied'] += 1
                  else:
                      result['failed'] += 1
                  if not settings['continue_on_access_denied']:
                      raise
                  return result

              for page in pages:
                  for volume in page.get('Volumes', []):
                      if settings['max_volumes_per_run'] and (result['would_delete'] + result['deleted'] + result['would_snapshot'] + result['snapshots_created']) >= settings['max_volumes_per_run']:
                          result['stopped_due_to_max_volumes_per_run'] = True
                          return result

                      result['evaluated'] += 1
                      volume_id = volume.get('VolumeId')
                      state = volume.get('State')
                      attachments = volume.get('Attachments', [])
                      size_gib = volume.get('Size')
                      volume_type = volume.get('VolumeType')
                      encrypted = volume.get('Encrypted')
                      availability_zone = volume.get('AvailabilityZone')
                      age_days = volume_age_days(volume)
                      tag_map = tags_to_dict(volume.get('Tags', []))

                      if state != 'available' or attachments:
                          result['skipped_attached'] += 1
                          continue

                      result['unattached'] += 1

                      if age_days is None or age_days < settings['minimum_unattached_age_days']:
                          result['skipped_too_new'] += 1
                          continue

                      ignore, ignore_reason = has_ignore_tag(tag_map, settings['ignore_tag_keys'], settings['ignore_tag_pairs'])
                      if ignore:
                          result['skipped_ignore_tag'] += 1
                          result['candidates'].append({
                              'volume_id': volume_id,
                              'age_days': age_days,
                              'size_gib': size_gib,
                              'volume_type': volume_type,
                              'availability_zone': availability_zone,
                              'action': 'skipped_ignore_tag',
                              'reason': ignore_reason,
                              'tags': tag_map
                          })
                          continue

                      if not has_approval_tag(tag_map, settings):
                          result['skipped_missing_approval_tag'] += 1
                          result['candidates'].append({
                              'volume_id': volume_id,
                              'age_days': age_days,
                              'size_gib': size_gib,
                              'volume_type': volume_type,
                              'availability_zone': availability_zone,
                              'action': 'skipped_missing_approval_tag',
                              'required_tag': settings['approval_tag_key'] + '=' + settings['approval_tag_value'],
                              'tags': tag_map
                          })
                          continue

                      result['eligible'] += 1
                      action_mode = settings['action_mode']
                      candidate = {
                          'volume_id': volume_id,
                          'age_days': age_days,
                          'size_gib': size_gib,
                          'volume_type': volume_type,
                          'encrypted': encrypted,
                          'availability_zone': availability_zone,
                          'tags': tag_map,
                          'action_mode': action_mode
                      }

                      if action_mode == 'report-only':
                          result['candidates'].append(candidate)
                          continue

                      wants_snapshot = action_mode in ('snapshot-only', 'snapshot-and-delete')
                      wants_delete = action_mode in ('delete-only', 'snapshot-and-delete')

                      if wants_delete and settings['snapshot_before_delete'] and not wants_snapshot:
                          result['failed'] += 1
                          result['failures'].append({
                              'volume_id': volume_id,
                              'error_code': 'SafetyBlocked',
                              'error_message': 'SnapshotBeforeDelete=true blocks delete-only mode.'
                          })
                          continue

                      if settings['dry_run']:
                          if wants_snapshot:
                              result['would_snapshot'] += 1
                          if wants_delete:
                              result['would_delete'] += 1
                          candidate['action'] = 'would_' + action_mode
                          result['candidates'].append(candidate)
                          continue

                      snapshot_id = None
                      if wants_snapshot:
                          try:
                              snapshot_id = create_remediation_snapshot(ec2, volume, region)
                              result['snapshots_created'] += 1
                              result['snapshots'].append({'volume_id': volume_id, 'snapshot_id': snapshot_id})
                          except ClientError as e:
                              code = e.response.get('Error', {}).get('Code', 'Unknown')
                              message = e.response.get('Error', {}).get('Message', str(e))
                              result['failures'].append({'volume_id': volume_id, 'operation': 'CreateSnapshot', 'error_code': code, 'error_message': message})
                              if code in ('AccessDenied', 'AccessDeniedException', 'UnauthorizedOperation') or 'explicit deny' in message.lower():
                                  result['access_denied'] += 1
                              else:
                                  result['failed'] += 1
                              if not settings['continue_on_access_denied']:
                                  raise
                              continue

                      if wants_delete:
                          try:
                              ec2.delete_volume(VolumeId=volume_id)
                              result['deleted'] += 1
                              deleted_record = dict(candidate)
                              deleted_record['snapshot_id'] = snapshot_id
                              result['deleted_volumes'].append(deleted_record)
                          except ClientError as e:
                              code = e.response.get('Error', {}).get('Code', 'Unknown')
                              message = e.response.get('Error', {}).get('Message', str(e))
                              result['failures'].append({'volume_id': volume_id, 'operation': 'DeleteVolume', 'error_code': code, 'error_message': message})
                              if code in ('AccessDenied', 'AccessDeniedException', 'UnauthorizedOperation') or 'explicit deny' in message.lower():
                                  result['access_denied'] += 1
                              else:
                                  result['failed'] += 1
                              if not settings['continue_on_access_denied']:
                                  raise

              return result

          def handler(event, context):
              settings = {
                  'excluded_regions': split_csv(os.environ.get('EXCLUDED_REGIONS_CSV', '')),
                  'dry_run': env_bool('DRY_RUN', True),
                  'minimum_unattached_age_days': env_int('MINIMUM_UNATTACHED_AGE_DAYS', 30),
                  'require_approval_tag': env_bool('REQUIRE_APPROVAL_TAG', True),
                  'approval_tag_key': os.environ.get('APPROVAL_TAG_KEY', 'CostOptApproved'),
                  'approval_tag_value': os.environ.get('APPROVAL_TAG_VALUE', 'true'),
                  'ignore_tag_keys': split_csv(os.environ.get('IGNORE_TAG_KEYS_CSV', '')),
                  'ignore_tag_pairs': parse_tag_pairs(os.environ.get('IGNORE_TAG_PAIRS_CSV', '')),
                  'action_mode': os.environ.get('ACTION_MODE', 'report-only'),
                  'snapshot_before_delete': env_bool('SNAPSHOT_BEFORE_DELETE', True),
                  'max_volumes_per_run': env_int('MAX_VOLUMES_PER_RUN', 50),
                  'continue_on_access_denied': env_bool('CONTINUE_ON_ACCESS_DENIED', True),
              }

              if isinstance(event, dict):
                  if 'dry_run' in event:
                      settings['dry_run'] = bool(event['dry_run'])
                  if 'require_approval_tag' in event:
                      settings['require_approval_tag'] = bool(event['require_approval_tag'])
                  if 'minimum_unattached_age_days' in event:
                      settings['minimum_unattached_age_days'] = int(event['minimum_unattached_age_days'])
                  if 'action_mode' in event:
                      settings['action_mode'] = str(event['action_mode'])
                  if 'snapshot_before_delete' in event:
                      settings['snapshot_before_delete'] = bool(event['snapshot_before_delete'])
                  if 'max_volumes_per_run' in event:
                      settings['max_volumes_per_run'] = int(event['max_volumes_per_run'])
                  if 'target_regions' in event and event['target_regions']:
                      os.environ['TARGET_REGIONS_CSV'] = ','.join(event['target_regions'])
                  if 'excluded_regions' in event and event['excluded_regions']:
                      settings['excluded_regions'] = list(event['excluded_regions'])

              if settings['action_mode'] not in ('report-only', 'snapshot-only', 'delete-only', 'snapshot-and-delete'):
                  settings['action_mode'] = 'report-only'

              summary = {
                  'started_at': utc_now_iso(),
                  'dry_run': settings['dry_run'],
                  'minimum_unattached_age_days': settings['minimum_unattached_age_days'],
                  'require_approval_tag': settings['require_approval_tag'],
                  'approval_tag': settings['approval_tag_key'] + '=' + settings['approval_tag_value'],
                  'action_mode': settings['action_mode'],
                  'snapshot_before_delete': settings['snapshot_before_delete'],
                  'ignore_tag_keys': settings['ignore_tag_keys'],
                  'ignore_tag_pairs': settings['ignore_tag_pairs'],
                  'max_volumes_per_run': settings['max_volumes_per_run'],
                  'excluded_regions': settings['excluded_regions'],
                  'regions': [],
                  'totals': {
                      'evaluated': 0,
                      'unattached': 0,
                      'eligible': 0,
                      'would_snapshot': 0,
                      'snapshots_created': 0,
                      'would_delete': 0,
                      'deleted': 0,
                      'skipped_attached': 0,
                      'skipped_too_new': 0,
                      'skipped_missing_approval_tag': 0,
                      'skipped_ignore_tag': 0,
                      'access_denied': 0,
                      'failed': 0
                  },
                  'region_results': []
              }

              try:
                  regions = get_enabled_regions(settings['excluded_regions'])
                  summary['regions'] = regions
                  for region in regions:
                      try:
                          region_result = scan_region(region, settings)
                      except Exception as e:
                          region_result = {
                              'region': region,
                              'evaluated': 0,
                              'unattached': 0,
                              'eligible': 0,
                              'would_snapshot': 0,
                              'snapshots_created': 0,
                              'would_delete': 0,
                              'deleted': 0,
                              'skipped_attached': 0,
                              'skipped_too_new': 0,
                              'skipped_missing_approval_tag': 0,
                              'skipped_ignore_tag': 0,
                              'access_denied': 0,
                              'failed': 1,
                              'failures': [{'error_code': type(e).__name__, 'error_message': str(e), 'trace': traceback.format_exc()}],
                              'candidates': [],
                              'snapshots': [],
                              'deleted_volumes': []
                          }
                      summary['region_results'].append(region_result)
                      for key in summary['totals']:
                          summary['totals'][key] += int(region_result.get(key, 0) or 0)
              finally:
                  summary['ended_at'] = utc_now_iso()
                  print(json.dumps(summary, indent=2, default=str))
              return summary

  RemediatorScheduleRule:
    Type: AWS::Events::Rule
    Condition: IsScheduleEnabled
    Properties:
      Name: !Sub '${ProjectName}-schedule'
      Description: Scheduled run for Unattached EBS Volume Remediator.
      ScheduleExpression: !Ref ScheduleExpression
      State: ENABLED
      Targets:
        - Arn: !GetAtt RemediatorFunction.Arn
          Id: UnattachedEbsVolumeRemediatorTarget
          Input: '{"source":"eventbridge-schedule"}'

  RemediatorSchedulePermission:
    Type: AWS::Lambda::Permission
    Condition: IsScheduleEnabled
    Properties:
      FunctionName: !Ref RemediatorFunction
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt RemediatorScheduleRule.Arn

Outputs:
  RemediatorFunctionName:
    Description: Lambda function name.
    Value: !Ref RemediatorFunction

  RemediatorFunctionArn:
    Description: Lambda function ARN.
    Value: !GetAtt RemediatorFunction.Arn

  DryRunSetting:
    Description: Current DryRun setting.
    Value: !Ref DryRun

  ActionModeSetting:
    Description: Current ActionMode setting.
    Value: !Ref ActionMode

  MinimumUnattachedAgeDaysSetting:
    Description: Current minimum unattached age setting.
    Value: !Ref MinimumUnattachedAgeDays

  RequireApprovalTagSetting:
    Description: Current RequireApprovalTag setting.
    Value: !Ref RequireApprovalTag

  ManualDryRunExample:
    Description: Example manual dry-run invocation payload.
    Value: !Sub 'aws lambda invoke --function-name ${RemediatorFunction} --cli-binary-format raw-in-base64-out --payload ''{"dry_run":true}'' response.json'

  ManualBatchCleanupDryRunExample:
    Description: Example unattached EBS volume batch cleanup dry-run payload.
    Value: !Sub 'aws lambda invoke --function-name ${RemediatorFunction} --cli-binary-format raw-in-base64-out --payload ''{"dry_run":true,"require_approval_tag":false,"minimum_unattached_age_days":30,"action_mode":"snapshot-and-delete","max_volumes_per_run":25}'' response.json'
